package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.common.Consts;
import com.github.aloxc.plugin.restplus.entity.RestConfig;
import com.github.aloxc.plugin.restplus.entity.Show;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.github.aloxc.plugin.restplus.navigator.RestServiceDetail;
import com.github.aloxc.plugin.restplus.navigator.RestServicesNavigator;
import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
 *
 * @author leero
 */
public class ShowListener extends MouseAdapter implements ActionListener{
    private Project project;
    public ShowListener(Project project) {
        this.project = project;
    }

    @Override
    public void mouseClicked(MouseEvent event) {
        Component showButton = (JButton)event.getSource();
        int x = event.getX();
        int y = event.getY() + 5;
        JPopupMenu menu = new JPopupMenu();
        JMenuItem code = new JMenuItem(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.response.show.code.text"));
        code.setName(Show.CODE.getType());
        JMenuItem tree = new JMenuItem(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.response.show.tree.text"));
        tree.setName(Show.TREE.getType());

        code.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        tree.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        code.setIcon(Consts.Icons.CODE);
        tree.setIcon(Consts.Icons.TREE);
        RestConfig config = project.getComponent(RestServicesNavigator.class).getConfig();
        menu.add(code);
        menu.add(tree);
        code.addActionListener(this);
        tree.addActionListener(this);
        menu.show(showButton, x, y);
        JMenuItem curItem = null;
        if (config == null) {
            curItem = code;
        }
        Show show = Show.get();
        if(show == null){
            curItem = code;
            show = Show.CODE;
            Show.set(show);
        }
        String showName = Show.get().getType();
        if (code.getName().equals(showName)) {
            curItem = code;
        } else {
            curItem = tree;
        }
        curItem.setSelected(true);
        curItem.setIcon(Consts.Icons.CUR);
        curItem.setForeground(Consts.MAIN_COLOR);
        curItem.setBackground(Consts.COOKIE_BACKGROUND_COLOR);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        String showType = ((JMenuItem) event.getSource()).getName();
        Show.set(Show.getByType(showType));
        RestServiceDetail restServiceDetail = project.getComponent(RestServiceDetail.class);
        restServiceDetail.removeResponseTab();
    }
}
